package com.xhs.hawaii.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhs.hawaii.common.utils.HttpUtils;
import org.apache.http.client.methods.RequestBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tangchuang
 * @version 1.0
 * @since 2018/1/25
 */
@Component
public class SsoService {

    @Value("${sso.url}")
    private String url;

    public UserInfo getUserInfo(String token) {
        RequestBuilder requestBuilder = RequestBuilder.get(url);
        requestBuilder.addHeader("Authorization", token);
        String result = HttpUtils.execute(requestBuilder.build());

        JSONObject jo = JSON.parseObject(result);
        if (!jo.getBooleanValue("success")) {
            throw new BusinessException("invalid token");
        }
        JSONObject jData = jo.getJSONObject("data");
        String userNo = jData.getString("account_no");
        String name = jData.getString("name");
        String id = jData.getString("user_id");
        String email = jData.getString("email");
        JSONArray permissions = jData.getJSONArray("permissions");
        List<String> ps;
        if (permissions == null || permissions.isEmpty()) {
            ps = new ArrayList<>(0);
        } else {
            ps = permissions.toJavaList(String.class);
        }
        return new UserInfo().setId(id).setName(name).setEmail(email).setPermissions(ps);
    }

}
